#include <iostream>
#include <string>
#include <cstdlib>
#include "oj_common/oj_log.h"
#include "oj_server/oj_server.h"
#define RED_TEXT "\x1b[31m"
#define RESET_TEXT "\x1b[0m"

void UsageDocument(const std::string& proc) {
    std::cout << RED_TEXT << "\nUsage: " << proc << " [ip(optional)] [port]\nsuch as: " << proc << " 0.0.0.0 8080" << RESET_TEXT << std::endl;
}

bool isValidPort(const char* portStr) {
    char* end;
    long port = std::strtol(portStr, &end, 10);
    return *end == '\0' && port > 0 && port <= 65535; // 检查转化的最后一个结果是否结束可使用 *end == '\0'
}

int main(int argc, char *argv[]) {
    uint16_t port;
    std::string ip = "0.0.0.0";  // Default IP

    if (argc < 2 || argc > 3) {
        UsageDocument(argv[0]);
        return -1;
    }

    if (argc == 2) {
        if (!isValidPort(argv[1])) {
            UsageDocument(argv[0]);
            return -1;
        }
        port = static_cast<uint16_t>(std::stoi(argv[1]));
    } else if (argc == 3) {
        ip = argv[1];
        if (!isValidPort(argv[2])) {
            UsageDocument(argv[0]);
            return -1;
        }
        port = static_cast<uint16_t>(std::stoi(argv[2]));
    }

    ojlb::oj_common::OjLog::setShieldLevel("trace");
    ojlb::oj_common::OjLog::info("启动 OJ 项目");

    ojlb::oj_server::OjServer server(port, ip);

    return 0;
}
